package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject





/**
 *
 * @Title: waterOffuser
 * @Description:智慧停水--智能客服 对接获取当前用户编号停水状态--外部接口
 * @author: cheih
 * @date 2021-10-27 10:28:00
 *
 */

public class waterOffuser implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(waterOffuser.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setContentType("application/json;charset=UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			
			
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			def timestamp = GetJV(inObject, "timestamp");//时间戳
			def sign = GetJV(inObject, "sign");//密钥

			log.debug("解析信息-" +"	timestamp: " + timestamp+"	sign: " + sign);
			long startTime = System.currentTimeMillis();
			String reJson = null;
			long endTime = 0;

			String apiid = "waterOff";
			String apikey = "55bd38420d354822bdb789284fac4ab3";
			String signfront = "";
			String signafter = ""

			signfront="apiid"+"="+apiid+"&"+"apikey"+"="+apikey+"&"+"timestamp"+"="+timestamp;
			log.debug("sign加密MD5前："+signfront);
			signafter=Util.getMD5Str(signfront);
			log.debug("sign加密MD5后："+signafter);
			
			if(!sign.equals(signafter)) {
				log.debug("signafter不存在");
				endTime = System.currentTimeMillis();
				reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用处理时长(毫秒):" + (endTime - startTime) + "\"}";
				return reJson;
			}

			String usercode = GetJV(inObject, "usercode");
			
			//非空校验
			String dealMessage = "";
			if (isNull(usercode)) {
				dealMessage = isNullMSG("usercode", usercode);
				//log.warn("调用参数非空校验异常:" + dealMessage);
				endTime = System.currentTimeMillis();
				outData = "{\"resultcode\":\"0\",\"resultmessage\":\"调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\"}";
			}else {
				log.debug("入参：usercode"+usercode);
				def getSelectSQL = eliteBean.chaxun_sql("SELECT wos.wateroffsmsguid, wos.wateroffsmsname ,wos.cutoffwater, wos.content, CONVERT (VARCHAR (100),	wos.waterontime,20) as waterontime, CONVERT (VARCHAR (100),	wos.waterofftime,20) as waterofftime,case when count(*)>1 then 'true' else 'false' end as wateroffcode from DocumentOut d left join waterOffSmsbatch  wos  on d.sub_doctype=wos.wateroffsmsguid where 1=1 and wos.waterofftime <= GETDATE() AND wos.waterontime >= GETDATE()  and d.stringfield1='智慧停水发送' and d.ucisid='" + usercode + "' group by wos.wateroffsmsguid, wos.wateroffsmsname, wos.cutoffwater, wos.content, wos.waterofftime, wos.waterontime", "dataSource");
				
				//def result,wateroffsmsguid,wateroffsmsname,content,waterofftime,waterontime="";
				if (getSelectSQL.size() > 0) {
					def reJoson = Util.getJsonFromList(getSelectSQL);
					/*
					result = getSelectSQL.get(0).get("result");
					wateroffsmsguid = getSelectSQL.get(0).get("wateroffsmsguid");
					wateroffsmsname = getSelectSQL.get(0).get("wateroffsmsname");
					content = getSelectSQL.get(0).get("content");
					waterofftime = getSelectSQL.get(0).get("waterofftime");
					waterontime = getSelectSQL.get(0).get("waterontime");
					*/
					endTime = System.currentTimeMillis();
					//outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"wateroffcode\":" + result + "}";
					outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + reJoson + "}";
				}else{
					endTime = System.currentTimeMillis();
					outData = "{\"resultcode\":\"2\",\"resultmessage\":\"处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
				}
			}
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
		}

		log.debug("短信数据接入处理完成返回结果:" + outData);

		return outData;
	}

		// 解析Json值
		public static String GetJV(JSONObject inJson, String getKey) {
			String Rev_Value = null;
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e1) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
					} catch (Exception e2) {
						try {
							Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
						} catch (Exception e3) {
							Rev_Value = "";
						}
					}
				}
			} finally {
				if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
					Rev_Value = "";
				} else {
				}
			}
			log.debug("解析-k=" + getKey + " v=" + Rev_Value);
			return Rev_Value;
		}


		// 非空校验isNull
		public static boolean isNull(String value) {

			boolean reFlag = true;
			if (value == "" || value.length() <= 0) {
				reFlag = true;
			} else {
				reFlag = false;
			}
			log.debug(reFlag);
			return reFlag;
		}

		// 非空校验isNullMSG
		public static String isNullMSG(String key, String value) {

			String reResult = "";
			if (value == "" || value.length() <= 0) {
				reResult = key + "必填字段;";
			}
			return reResult;
		}
		
		//判断时间是否在9点到21点时间段 1在 0 不在
		public static String checkTimeIsBetween(String timeString) throws ParseException {
			String format = "HH:mm:ss";
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
	 
			Date timeDate1 = simpleDateFormat.parse(timeString);
	 
			Date startTime = simpleDateFormat.parse("09:00:00");
			Date endTime = simpleDateFormat.parse("21:00:00");
	 
			String dateresult;
			if (timeDate1.before(startTime) || timeDate1.after(endTime)) {//此时间不 在当天9点至21点之间
				dateresult="0";
			}else{//此时间在当天9点至21点之间
				dateresult="1";
			}
			return dateresult;
		}

	}
